package com.dy.vueadminservice.config;

import com.dy.vueadminservice.service.users.UserInfoService;
import com.dy.vueadminservice.service.users.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangdeyao
 */
@Component
public class DemoFilter extends GenericFilterBean {

    private final UserInfoService userInfoService;

    @Autowired
    public DemoFilter(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        // 得到当前的认证信息  动态刷新权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            UserDTO userDTO = userInfoService.getInfo();
            if (userDTO != null) {
                List<GrantedAuthority> updatedAuthorities = userDTO.getPermission().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                // 重置认证信息
                // 生成新的认证信息
                auth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
